/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package no.hin.stg.beans;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.xml.bind.JAXBException;
import no.hin.stg.jxb.ObjectFactory;
import no.hin.stg.jxb.Project;
import no.hin.stg.jxb.Unit;
import no.hin.stg.db.MysqlAdapter;
import no.hin.stg.xml.parser.Parser;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.xml.sax.SAXException;

/**
 *
 * @author 490501
 */
@ManagedBean
@SessionScoped
public class ProjectBean implements Serializable {
    //variables for projcet uploading
    private UploadedFile uploadedXML;
    private UIComponent uploadFileUIComponent;
    
    //constants for generation
    private final int MINQUANTITY = 1;
    private final int MAXQUANTITY = 100;
    /**
     * <p>contains message text which canbe return to faces context
     */
    private String message, stage;
    /**
     * uses to create objects of project hierarchy
     */
    private ObjectFactory obf;
    /**
     * <p>"root" class for an project, contains all other elements of a project
     */
    private Project currentProject;
    //
    //variables for unit generations
    //
    private int quantity;
    private String[] location = {"ANY", "FYLKE", "COMMUNE"};
    private String currentLocation;
    private String currentFylke;
    private String currentCommune;
    HashMap<Integer, String> communer;
    
    //other
    private static final Logger LOG = Logger.getLogger(ProjectBean.class.getName());

    public ProjectBean() {
        this.obf = new ObjectFactory();
        this.currentProject = obf.createProject();
        this.currentProject.setDescription(obf.createDescription());
        this.currentProject.setUnits(obf.createUnits());
        this.currentProject.setProfiles(obf.createProfiles());
    }

    /**
     *
     */
    public String upload() throws IOException {
        try {
            //TODO implement loadin from extern xml file
            InputStream stream = uploadedXML.getInputStream();
            Parser p = new Parser("E:\\NetBeansProjects\\SysUtvModelParserJAXB\\xml-resources\\jaxb\\jaxbinding\\v1s.xsd");
            p.loadXML(stream);
            this.currentProject = p.getProject();
            LOG.log(Level.SEVERE, "project from xml loaded successfully");
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(uploadFileUIComponent.getClientId(), new FacesMessage("Test msg"));
            return "projectLoadingDone";
        } catch (JAXBException ex) {
            Logger.getLogger(ProjectBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(ProjectBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "projectLoadingFailed";
    }

    /**
     * <p>creates one simple unit <p>Look at xsd schema to get information about
     * required information for unit
     */
    public void createSimpleUnit() {
        //TODO implement it 
    }

    /**
     * <p>creates one advanced unit <p>Look at xsd schema to get information
     * about required information for unit
     */
    public void createAdvancedUnit() {
        //TODO imlement it 
    }

    /**
     * <p>generates units and saves in in current loaded project
     */
    public void generateUnits() {
        //TODO implements
        for (int i = 0; i < this.quantity; i++) {
            Unit _u = obf.createUnit();
            _u.setSimple(obf.createSimpleMode());
            
        }
    }

    /**
     * <p> @param e ValueChangeListener som older rede på ny og gammel verdi av
     * element den tilhører
     */
    public void loadLocationWindow(ValueChangeEvent e) {
        this.currentLocation = (String) e.getNewValue();
    }

    public HashMap<Integer, String> getFylker() throws SQLException {
        if(this.currentCommune != null) {
            this.currentCommune = null;
        }
        MysqlAdapter ms = new MysqlAdapter();
        return ms.getFylker();
    }

    
    /**
     * 
     * @param e value change event from jsf form
     * @throws SQLException if any SQL exceptions occurs
     */
    public void getCommuner(ValueChangeEvent e) throws SQLException {
        String fylkeName = (String) e.getNewValue();
        MysqlAdapter ms = new MysqlAdapter();
        HashMap<Integer, String> temp = ms.getFylker();
        int id;
        for(Entry val : temp.entrySet()){
            if(((String)val.getValue()).equals(fylkeName)){
                id = (Integer)val.getKey();
                communer = ms.getKommuner(id);
            }
        }
    }

    
    /**
     * ***********************************************************************
     */
    public synchronized Project getCurrentProject() {
        return currentProject;
    }

    public void setCurrentProject(Project currentProject) {
        this.currentProject = currentProject;
    }

    public synchronized String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public synchronized String getStage() {
        return stage;
    }

    public void setStage(String stage) {
        this.stage = stage;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int getMINQUANTITY() {
        return MINQUANTITY;
    }

    public int getMAXQUANTITY() {
        return MAXQUANTITY;
    }

    public String[] getLocation() {
        return location;
    }

    public String getCurrentLocation() {
        return currentLocation;
    }

    public synchronized HashMap<Integer, String> getCommuner() {
        return communer;
    }

    public synchronized String getCurrentFylke() {
        return currentFylke;
    }

    public void _setCurrentFylke(ValueChangeEvent e) {
        this.currentFylke = (String)e.getNewValue();
    }

    public synchronized String getCurrentCommune() {
        return currentCommune;
    }

    public void _setCurrentCommune(ValueChangeEvent e) {
        this.currentCommune = (String)e.getNewValue();
    }

    public UploadedFile getUploadedXML() {
        return uploadedXML;
    }

    public void setUploadedXML(UploadedFile uploadedXML) {
        this.uploadedXML = uploadedXML;
    }

    public UIComponent getUploadFileUIComponent() {
        return uploadFileUIComponent;
    }

    public void setUploadFileUIComponent(UIComponent uploadFileUIComponent) {
        this.uploadFileUIComponent = uploadFileUIComponent;
    }
    
    
    
 
    
    
    
}
